/*
	Display detail book item and another functions: Download, Buy, Play audio, Comment, Annotation, Quote, Share, Add favorite
*/
var bookVM = function () {

	// Variables and localizations for Book page
	var datacontext = new DataContext(),
	list = ko.observableArray([]),
	listComment = ko.observableArray([]),
	listAnnotation = ko.observableArray([]),
	soundDuration = ko.observable(0),
	needAddToFavorite = false,
	soundCurrentPossision = ko.observable(0),
	FavoriteFolder = ko.observable("Default_folder"),
	FavoriteFolderLabel = ko.observable(getLocalizeText('defaultFolder')),
	isPlaying = ko.observable(false),
	isDisplayPlayer = ko.observable(false),
	isHaveAudio = ko.observable(false),
    isEditFont = ko.observable(false),
	numberFreeBooks = ko.observable(6),
	buyTheBookHTML = ko.observable(),
	title = ko.observable(getLocalizeText('Details')),
	strGetSummary = ko.observable(getLocalizeText('getSummary')),
	strAudio = ko.observable(getLocalizeText('audio')),
	strComments = ko.observable(getLocalizeText('comments')),
	strShareEmail = ko.observable(getLocalizeText('shareEmail')),
	strShareEmailTo = ko.observable(getLocalizeText('eMail')),
	strShareEmailContent = ko.observable(getLocalizeText('comments')),
	strShareEmailBody = ko.observable(getLocalizeText('shareViaEmailBody')),
	strAnnotations = ko.observable(getLocalizeText('annotations')),
	strQuotes = ko.observable(getLocalizeText('quotes')),
	strRating = getLocalizeText('rating'),
	strTakeAways = getLocalizeText('takeAways'),
	strWhatYouWillLearn = getLocalizeText('whatYouWillLearn'),
	strRecommendation = getLocalizeText('recommendation'),
	strAbstract = getLocalizeText('abstract'),
	strAboutTheAuthors = getLocalizeText('aboutTheAuthors'),
	strThereAreCurrently = ko.observable(getLocalizeText('thereAreCurrently')),
	strCommentsOnThisTitle = ko.observable(getLocalizeText('commentsOnThisTitle')),
	strAddAComment = ko.observable(getLocalizeText('addAComment')),
	strPost = ko.observable(getLocalizeText('post')),
	strCancel = ko.observable(getLocalizeText('cancel')),
	strFavorites = ko.observable(getLocalizeText('favorites')),
	strWouldYouLike = ko.observable(getLocalizeText('wouldYouLikeTo')),
	strYes = ko.observable(getLocalizeText('yes')),
	strNo = ko.observable(getLocalizeText('no')),
	strTextOnly = ko.observable(getLocalizeText('textOnly')),
	strTextAndAudio = ko.observable(getLocalizeText('textAndAudio')),
    strRemaining    = ko.observable(getLocalizeText('remaining')),
    strFonts        = ko.observable(getLocalizeText('fonts')),
    strBackground   = ko.observable(getLocalizeText('background')),
    strWhite        = ko.observable(getLocalizeText('white')),
    strSepia        = ko.observable(getLocalizeText('sepia')),
    strBlack        = ko.observable(getLocalizeText('black')),
	heightOfScreen = ko.observable($(window).height()),
	entity = ko.observable(),
	bookID = ko.observable(),
	mediaTimer = null,
	currentPosition = 0,	// [WP]
    isPausing = false,		// [WP]
	fontSizeTitle = ko.observable(localStore.get("book_detail_font_size") == null ? 16 : localStore.get("book_detail_font_size")),
	fontSizeContent = ko.observable(fontSizeTitle() - 2),
    fontName = ko.observable(localStore.get("book_detail_font_name") == null ? "arial" : localStore.get("book_detail_font_name")),
	topLi = ko.observable(Math.round(fontSizeContent() / 2) + 3),
	fontSizeSubTitle = ko.observable(fontSizeTitle() - 5),
    backgroundColorName = ko.observable(localStore.get("book_detail_background_color_name") == null ? "white" : localStore.get("book_detail_background_color_name")),
    textColorName = ko.observable(localStore.get("book_detail_text_color_name") == null ? "black" : localStore.get("book_detail_text_color_name")),
    textDefaultFontNameForPlatform = isiOS ? "Arial" : "GaFont",
    textFontName = ko.observable(localStore.get("book_detail_font_name") == null ? textDefaultFontNameForPlatform : localStore.get("book_detail_font_name")),
    isBuletWhite = ko.observable(backgroundColorName() == 'black' ? true : false),
    fontNameList = ko.observable([]),
		/*
			Get book detail: always get data and store to local
			+ id: book id
			+ isServer: FALSE check local storage
		*/
		// [CHECK] in Android 4.4 for image displaying
		getDetail = function (id, isServer, callBackWhenViewBook) {
			bookID(id);
			list([]);
			entity(null);
            createFontList();
			isLoading = true;
			showLoadingDialog();
			return datacontext.book.getDetail({
				isServer: isServer,
				results: list,
				id: id,
				callbackFunc: function () {
					afterGetDetail(list()[0].object);
                    if (callBackWhenViewBook){
                        callBackWhenViewBook(true);
                    }
				},
				key: "saveFilebookDetail_" + systemLanguage + '' + id
			}).done(function () {
				CheckExpireSession(
					list, 
					false,
					function() {
						getDetail(id, isServer);
					}, 
					function(entityresult) {
                        afterGetDetail(entityresult);
                        if (callBackWhenViewBook){
                            callBackWhenViewBook(true);
                        }
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                        /* session expired */
                                                        getDetail(id, isServer);
                                                    },
                                                    function(){
                                                        /* not expire */
                                                        if (callBackWhenViewBook){
                                                            callBackWhenViewBook(false);
                                                        }
                                                    });
                
			});
		},

		afterGetDetail = function(obj) {
			entity(obj);
			if (entity() != undefined) {
				entity().overView.dataId(bookID());
				// Set comments
				var numberCommentInGetDetail = localStore.get('munber_comment_book_' + bookID()) == undefined ? 0 : parseInt(localStore.get('munber_comment_book_' + bookID()));
				if (localStore.get('munber_comment_book_' + bookID()) != null) {
					if (numberCommentInGetDetail > entity().overView.numberComment()) {
						entity().overView.numberComment(localStore.get('munber_comment_book_' + bookID()));
					} else {
						localStore.save('munber_comment_book_' + bookID(), entity().overView.numberComment());
					}
				}
				// Check audio
				if (entity().header.audioFile() == null || entity().header.audioFile() == "") {
					isHaveAudio(false);
					strAudio(getLocalizeText("noAudio"));
				} else {
					isHaveAudio(true);
					strAudio(getLocalizeText("audio"));
				}
				/* check number free book */
                if (localStore.get("numberFreeBooks") == null && entity().overView.preview() == true) {
                    
                    numberFreeBooks(entity().overView.downloadsAvailable());
                } else if (entity().overView.preview() == true){
                    var numberFreeBookTemp = parseInt(localStore.get("numberFreeBooks"));
                    
                    if (entity().overView.downloadsAvailable() != -1 && numberFreeBookTemp > entity().overView.downloadsAvailable()){
                        numberFreeBooks(entity().overView.downloadsAvailable());
                    }
                    else{
                        numberFreeBooks(numberFreeBookTemp);
                    }
                }
                
                /* check and remove invalid value */
                if (numberFreeBooks() < 0){
                    numberFreeBooks(0);
                }
//                localStore.save("numberFreeBooks", numberFreeBooks());
                
				setTimeout(function applyScroll() {
					if (myScroll != null) {
						myScroll.refresh();
					}
					// [Android] [WP] [BB]
					if (!isiOS) {
						$("a").on('tap touch click', function (e) {
							if (isJqmGhostClick()) {
								return false;
							}
							e.stopPropagation();
							e.preventDefault();
							window.open($(this).attr('href'), "_system");
							return false;
						});	
					}					
				}, 200);
			}
            setTextColorDefault();
			hideLoadingDialog();
			isLoading = false;
		},

		// Download summary
		// [CHECK] in Android 4.4 after active
		activeBook = function () {
			if (!CanLoad())
				return;

			list([]);
			showLoadingDialog();
			isLoading = true;

			return datacontext.active.activeBook({
				results: list,
				dataId: bookID()
			}).done(function () {
				CheckExpireSession(
					list, 
					true,
					function() {
						isUserActionClick = false;
						activeBook();
					}, 
					function() {
                            
                            if (numberFreeBooks()!= 0){
                                numberFreeBooks(numberFreeBooks()-1);
                            }

                            localStore.save("numberFreeBooks", numberFreeBooks());

                           getDetail(bookID(), true);
                           model.isDisplayArrowDown(true);
                           setTimeout(function hideArrowDown() {
                                      model.isDisplayArrowDown(false);
                                      }, 5000);
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                        /* session expired */
                                                        isUserActionClick = false;
                                                        activeBook();
                                                    },
                                                    function(){
                                                        /* not expire */
                                                    });
			});
		},

		// Get content from server
		buyTheBook = function () {
			if (!CanLoad())
				return;

			/* check is buy the book or watch video */
			if (entity().header.fullText.type() == 'link') {
				var domainName = localStore.get(strDomainKey);
				window.open(domainName + "BuyBook.do?dataId=" + bookID(), "_system");
				return;
			}
			
			list([]);
			showLoadingDialog();
			isLoading = true;

			return datacontext.buy.buyTheBook({
				results: list,
				dataId: bookID()
			}).done(function () {
				CheckExpireSession(
					list, 
					true,
					function() {
						isUserActionClick = false;
						buyTheBook();
					}, 
					function (entityresult) {
						buyTheBookHTML(entityresult);
						model.viewBuyTheBook();
					});
			}).fail(function (e) {
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                        /* session expired */
                                                        isUserActionClick = false;
                                                        buyTheBook();
                                                    },
                                                    function(){
                                                        /* not expire */
                                                    });
			});
		},
        viewComments = function (){
            if (!CanLoad())
                return;
            comments();
        },
		// Get comments of book item
		comments = function (isServer) {
			list([]);
			showLoadingDialog();
			isLoading = true;

			return datacontext.comments.getComments({
				results: list,
				dataId: bookID(),
                key: "saveFileCommentBookID_" + bookID(),
                isServer:isServer,
                callbackFunc: function () {
                    afterGetComments(list()[0].object());
                    stopLoading();
                }
 
			}).done(function () {
				CheckExpireSession(
					list, 
					true,
					function() {
						comments(isServer);
					}, 
					function(entityresult) {
                                   afterGetComments(entityresult());
					});
			}).fail(function (e) {
				/* failed cause internet */
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                        /* session expired */
                                                        comments(isServer);
                                                    },
                                                    function(){
                                                        /* not expire */
                                                    });
			});
		},
        afterGetComments = function(listCommentTemp){
            listComment(listCommentTemp);
            if (listComment().length > 1) {
                entity().overView.numberComment(listComment().length);
            } else if (listComment().length > 0 && listComment()[0].name != 'getAbstract') {
                entity().overView.numberComment(1);
            } else {
                entity().overView.numberComment(0);
            }
            localStore.save('munber_comment_book_' + bookID(), entity().overView.numberComment());
            model.viewComments();
            if (myScroll != null) {
                myScroll.refresh();
            }
        },
		// Get annotations of book item
		getAnnotaions = function () {
            if (!CanLoad())
				return;
            list([]);

            showLoadingDialog();
            isLoading = true;

            return datacontext.annotations.getAnnotations({
                results: list,
                dataId: bookID(),
                key: "saveFileAnnotationBookID_" + bookID(),
                callbackFunc: function () {
                    stopLoading();
                    listAnnotation(list()[0].object());
                    if (listAnnotation().length > 0) {
                        model.viewAnnotations();
                    } else {
                        showPopup(getLocalizeText("noResultsFound"));
                    }
                }
            }).done(function () {
                CheckExpireSession(
                    list, 
                    true,
                    function() {
                        isUserActionClick = false;
                        getAnnotaions();
                    }, 
                    function(entityresult) {
                        listAnnotation(entityresult());
                        if (listAnnotation().length > 0) {
                            model.viewAnnotations();
                        } else {
                            showPopup(getLocalizeText("noResultsFound"));
                        }
                    });
            }).fail(function (e) {
                /* failed cause internet */
                    CheckExpireSessionErrorCallback(e,
                                                    function(){
                                                        /* session expired */
                                                        isUserActionClick = false;
                                                        getAnnotaions();
                                                    },
                                                    function(){
                                                        /* not expire */
                                                    });
            });
			
		},

		// Post comment and get list
		postComments = function () {
			if (!CanLoad())
				return;

			$('#comment-text').blur();
			if ($('#comment-text').val() == '') {
				showPopup(getLocalizeText('pleaseInputYourMessage'));
			} else {
				list([]);
				showLoadingDialog();
				isLoading = true;

				return datacontext.postComments.post({
					results: list,
					dataId: bookID(),
					comment: document.getElementById('comment-text').value
				}).done(function () {
					CheckExpireSession(
						list, 
						true,
						function() {
							isUserActionClick = false;
							postComments();
						}, 
						function() {
                            isUserActionClick = false;
                            comments(true);
                            showPopup(getLocalizeText('success'));
						});
				}).fail(function (e) {
                        CheckExpireSessionErrorCallback(e,
                                                        function(){
                                                        /* session expired */
                                                        isUserActionClick = false;
                                                        postComments();
                                                        },
                                                        function(){
                                                            /* not expire */
                                                        });
				});
			}
		},

		// Share book item via email
		postShareEmail = function () {
			if (!CanLoad())
				return;

			$('#share-email-to').blur();
			$('#share-email-content').blur();
			var strEmails = $('#share-email-to').val();
			var strSubject = getLocalizeText('shareViaEmailSubject');
			var strContent = $('#share-email-content').val();

			if (strEmails == '' || !model.isEmail(strEmails)) {
				showPopup(getLocalizeText('youNeedInputEmail'));
			} else if (strContent == '') {
				showPopup(getLocalizeText('pleaseInputYourMessage'));
			} else {
                /* send email here */
				list([]);
				showLoadingDialog();
				isLoading = true;

				return datacontext.postShareEmail.post({
					results: list,
					dataId: bookID(),
                    email: encodeURIComponent(strEmails),
                    text:encodeURIComponent(strContent)
				}).done(function () {
					CheckExpireSession(
						list, 
						true,
						function() {
							isUserActionClick = false;
							postShareEmail();
						}, 
						function() {
                            isUserActionClick = false;
                            showPopupWithCallback(getLocalizeText('success'), function () {
                                model.displayBookDetail();
                            });
						});
				}).fail(function (e) {
                        CheckExpireSessionErrorCallback(e,
                                                        function(){
                                                        /* session expired */
                                                        isUserActionClick = false;
                                                        postShareEmail();
                                                        },
                                                        function(){
                                                        /* not expire */
                                                        });
				});
			}
		},
        showHideFontEdit = function () {
            
            model.isViewSearch(false);
			model.isDisplayPopupAdd(false);
			model.isDisplayPopupMedia(false);
            hideBtnsShare();
            isEditFont(!isEditFont());

        },
        setShowHideFontEdit = function (isShow) {
            
            isEditFont(isShow);

        },
    
		// When user click on "A+" button
		increaseFontSize = function () {
			if (isLoading) {
				return;
			}
			if (fontSizeTitle() < maxFontSize) {
				fontSizeTitle(fontSizeTitle() - (-1));
				fontSizeSubTitle(fontSizeTitle() - 5);
				fontSizeContent(fontSizeTitle() - 2);
				topLi(Math.round(fontSizeContent() / 2) + 3);
				localStore.save("book_detail_font_size", fontSizeTitle());
			}
			setTextColorDefault();
		},

		// When user click on "A-" button
		decreaseFontSize = function () {
			if (isLoading) {
				return;
			}
			if (fontSizeTitle() > minFontSize) {
				fontSizeTitle(fontSizeTitle() - 1);
				fontSizeSubTitle(fontSizeTitle() - 5);
				fontSizeContent(fontSizeTitle() - 2);
				topLi(Math.round(fontSizeContent() / 2) + 3);
				localStore.save("book_detail_font_size", fontSizeTitle());
			}
			setTextColorDefault();
		},

		// Display popup to select
		// [DONE] Remove addToFavoriteItem with NULL
		addToFavorite = function () {
			if (isLoading) {
				return;
			}			
			model.isViewSearch(false);
			hideBtnsShare();
            setShowHideFontEdit(false);
			if (localStore.get("Favorite_book_id_" + bookID()) != null) {
				showPopup(getLocalizeText('thisBookExistOnYourFavorite'));
				return;
			}

			if (entity().overView.preview() == false) {
				if (entity().header.audioFile() != undefined && entity().header.audioFile().indexOf("http://") == 0) {
					displayPopupMedia(strCatchFolder + "/" + hashCode(entity().header.audioFile()) + ".mp3");
					return;
				} else {
					model.isDisplayPopupAdd(!model.isDisplayPopupAdd());
					applyIscrollForFolder('wrapper_scroll_folder');
					return;
				}
			}
            model.isDisplayPopupAdd(!model.isDisplayPopupAdd());
            applyIscrollForFolder('wrapper_scroll_folder');
		},

		/* 
			Handle add book item to favorite category
			+ item: favorite category
		*/
		addToFavoriteItem = function (item) {
				model.isDisplayPopupAdd(false);
				FavoriteFolder("Folder_" + item.folderID());
				FavoriteFolderLabel(item.folderName());
				list([]);
				showLoadingDialog();
				isLoading = true;

				return datacontext.editFavorite.add({
					results: list,
                    folder_id: item.folderID(),
                    data_id: bookID()
				}).done(function () {
                        if(list().length > 0){
                            CheckExpireSession(
                                list, 
                                true,
                                function() {
                                    addToFavoriteItem(item);
                                }, 
                                function(deleteResult) {
                                    saveOnLocal();
                                });
                        }
                        else{
                            ShowErrorMessage();
                            hideLoadingDialog();
                            isLoading = false;
                        }
				}).fail(function (e) {
                        CheckExpireSessionErrorCallback(e,
                                                        function(){
                                                        /* session expired */
                                                        addToFavoriteItem(item);
                                                        },
                                                        function(){
                                                        /* not expire */
                                                        });
				});
			
		},

		// Store favorite book item to local
		// [DONE] move new item: same as saveFavoriteOnLocal (in vm.overview.js)
		saveOnLocal = function () {
			localStore.save("Favorite_book_id_" + bookID(), true);
			SaveBookToLocalFirstPosition(FavoriteFolder(), bookID(), entity().overView);
			showPopup(getLocalizeText('addSuccessfulToFolder') + FavoriteFolderLabel());
		},

		// Use in bought book and have audio: Download audio file to local
		addWithMedia = function () {
			model.isDisplayPopupMedia(false);
			if (entity().header.audioFile().indexOf("http://") == 0) {
				needAddToFavorite = true;
				checkIfFileExists(strCatchFolder + "/" + hashCode(entity().header.audioFile()) + ".mp3");
			} else {
				if (isLogin) {
					model.isDisplayPopupAdd(true);
					applyIscrollForFolder('wrapper_scroll_folder');
					return;
				} 
				// [DONE] Remove all addToFavoriteItem with NULL
			}
		},

		// Use in bought book and have audio
		addWithoutMedia = function () {
			model.isDisplayPopupMedia(false);
			if (isLogin) {
				model.isDisplayPopupAdd(true);
				applyIscrollForFolder('wrapper_scroll_folder');
				return;
			}
		},

		// Hide popup
		closePopupMedia = function () {
			model.isDisplayPopupMedia(false);
		},

		// Show/Hide share button
		shareSocialNetwork = function () {
			if (isLoading) {
				return;
			}
			model.isViewSearch(false);
			model.isDisplayPopupAdd(false);
			model.isDisplayPopupMedia(false);
            setShowHideFontEdit(false);
			if (!model.isDisplayBtnsShare()) {
				showBtnsShare();
			} else {
				hideBtnsShare();
			}
		},
		
		shareFacebook = function () {
			hideBtnsShare();
			// [ANDROID]
			if (isAndroid)
				shareFacebookAndroid();
			// [iOS]
			if (isiOS)
				shareFacebookiOS();
			// [WP] [BB]
			if (isWP || isBB)
				shareFacebookWeb();
		},

		shareFacebookAndroid = function() {
			var url = getLocalizeText('iAmCurrentlyreading') + entity().overView.title();
			url = url + '\n' + entity().overView.author();
			url = url + '\n' + entity().overView.extraText();
			url = url + '\n' + 'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID();
			window.plugins.share.show({
					action: 'shareFacebook',
					message: url
				},
				function () {}, // Success function
				function () {} // Failure function
			);
			$('#popupSelectShare').popup("close");
		},

		shareFacebookiOS = function() {
			var url = 'http://www.facebook.com/dialog/feed?app_id=143891362343386';
			url = url + '&picture=' + entity().overView.thumbnailMedium();
			url = url + '&name=' + getLocalizeText('iAmCurrentlyreading') + entity().overView.title();
			url = url + '&caption=' + entity().overView.author();
			url = url + '&description=' + entity().overView.extraText();
			url = url + '&link=' + 'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID();
			url = url + '&message=' + '';
			url = url + '&redirect_uri=http://www.getabstract.com/demo';
			share.facebookWith(entity().overView.thumbnailMedium(),
				getLocalizeText('iAmCurrentlyreading') + entity().overView.title(),
				entity().overView.author(),
				entity().overView.extraText(),
				'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID());
		},

		shareFacebookWeb = function() {
			var url = 'http://www.facebook.com/dialog/feed?app_id=152414651615965';
			url = url + '&picture=' + entity().overView.thumbnailMedium();
			url = url + '&name=' + getLocalizeText('iAmCurrentlyreading') + entity().overView.title();
			url = url + '&caption=' + entity().overView.author();
			url = url + '&description=' + entity().overView.extraText();
			url = url + '&link=' + 'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID();
			url = url + '&message=' + '';
			url = url + '&redirect_uri=http://www.getabstract.com/social-confirmation';
			window.open(encodeURI(url), '_system', 'location=yes');

			$('#popupSelectShare').popup("close");
		},
		
		shareTwitter = function () {
			hideBtnsShare();
			// [ANDROID]
			if (isAndroid)
				shareTwitterAndroid();
			// [iOS]
			if (isiOS)
				shareTwitteriOS();
			// [WP] [BB]
			if (isWP || isBB)
				shareTwitterWeb();
		},

		shareTwitterAndroid = function() {
			var url = getLocalizeText('iAmCurrentlyreading') + entity().overView.title();
			url = url + '\n' + 'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID();
			window.plugins.share.show({
					action: 'shareTwitter',
					message: url
				},
				function () {}, // Success function
				function () {} // Failure function
			);
			$('#popupSelectShare').popup("close");
		},

		shareTwitteriOS = function() {
			var url = 'https://twitter.com/intent/tweet?source=webclient&text=';
			url = url + getLocalizeText('iAmCurrentlyreading') + entity().overView.title();
			url = url + ' - ' + 'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID();
			share.twitterWith(entity().overView.thumbnailMedium(),
				getLocalizeText('iAmCurrentlyreading') + entity().overView.title(),
				entity().overView.author(),
				'',
				'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID());
		},

		shareTwitterWeb = function() {
			var url = 'https://twitter.com/intent/tweet?source=webclient&text=';
			url = url + getLocalizeText('iAmCurrentlyreading') + entity().overView.title();
			url = url + ' - ' + 'http://www.getabstract.com/ShowAbstract.do?dataId=' + bookID();
			window.open(encodeURI(url), '_system', 'location=yes');
			$('#popupSelectShare').popup("close");
		},
        shareLinkedIn = function(){
            hideBtnsShare();
            share.shareLinkedIn(bookID(), entity().header.thumbnailMedium());
            
        },
		// Share book item via email
		shareEmail = function () {
			$('#popupSelectShare').popup("close");
			model.viewShareEmail();
		},

		hideBtnsShare = function () {
			if (!model.isDisplayBtnsShare()) {
				return;
			}
			$('#btnShareEmail').animate({
				right: '+=50',
				top: '-=30'
			}, 200, function () {
				model.isDisplayBtnsShare(false);
			});
			$('#btnShareFacebook').animate({
				right: '-=50',
				top: '-=30'
			}, 200, function () {});
			$('#btnShareTwitter').animate({
				top: '-=50',
                right: '-=20'
			}, 200, function () {});
            $('#btnShareLinkedIn').animate({
               right: '+=20',
               top: '-=50'
           }, 200, function () {});
			var countEmailFrame = 8;
			var rotageShareEmail = self.setInterval(function () {
				countEmailFrame -= 1;
				$('#btnShareEmail').removeClass('share-email-bg-' + countEmailFrame);
                $('#btnShareLinkedIn').removeClass('share-email-bg-' + countEmailFrame);
				$('#btnShareFacebook').removeClass('share-email-bg-' + countEmailFrame);
				$('#btnShareTwitter').removeClass('share-email-bg-' + countEmailFrame);
				if (countEmailFrame == 2) {
					window.clearInterval(rotageShareEmail);
				}
			}, 30);
		},

		showBtnsShare = function () {
            var rightOffset = $(window).width() - $('#nav-btn-share').offset().left - 40;
            $(".share-bg").css({
                                            right: rightOffset + 'px'
                                            });
            
			if (model.isDisplayBtnsShare()) {
				return;
			} else {
				model.isDisplayBtnsShare(true);
			}
            
			$('#btnShareEmail').animate({
				right: '-=50',
				top: '+=30'
			}, 200, function () {});
			$('#btnShareFacebook').animate({
				right: '+=50',
				top: '+=30'
			}, 200, function () {});
			$('#btnShareTwitter').animate({
				top: '+=50',
                right: '+=20'
			}, 200, function () {});
            $('#btnShareLinkedIn').animate({
                  top: '+=50',
                   right: '-=20'
                   
              }, 200, function () {});
			var countEmailFrame = 1;
			var rotageShareEmail = self.setInterval(function () {
				countEmailFrame += 1;
				$('#btnShareEmail').addClass('share-email-bg-' + countEmailFrame);
                $('#btnShareLinkedIn').addClass('share-email-bg-' + countEmailFrame);
				$('#btnShareFacebook').addClass('share-email-bg-' + countEmailFrame);
				$('#btnShareTwitter').addClass('share-email-bg-' + countEmailFrame);
				if (countEmailFrame == 7) {
					window.clearInterval(rotageShareEmail);
				}
			}, 30);
		},				
		
		my_media,

		// Media player handle
		onSuccess = function () {
			console.log("playAudio():Audio Success");
		},

		onError = function (error) {
			showPopup('code: ' + error.code + '\n' +
				'message: ' + error.message + '\n');
		},

		playMedia = function () {
			if (isJqmGhostClick())
				return;
			var audioPath = entity().header.audioFile();
			// [BB]
			if (isBB) {
				entity().header.audioFileDisplay(localPathForBB + strCatchFolder + '/' + hashCode(entity().header.audioFile()) + '.mp3');
				audioPath = entity().header.audioFileDisplay();
			}
			playMediaFile(audioPath);
			
		},

		playMediaFile = function (audioPath) {
			if (audioPath != null && audioPath != "") {
				// Create Media object from src
				if (my_media == null) {
					// [ANDROID] [iOS]
					if (isAndroid || isiOS){
						my_media = new Media(audioPath, onSuccess, onError);
					}
					// [BB]
					if (isBB) {
						my_media = new Audio(audioPath);
						my_media.seekable = true;
					}
					// [WP]
					if (isWP) {
						my_media = new Media(audioPath, onSuccess, onError, function onStatus(status) {
							if (status == 2) {
								if (isPausing) {
									isPausing = false;
									if (currentPosition > 0) {
										my_media.seekTo(currentPosition * 1000);
									}
								}
							}
						});
					}
				}
				if (mediaTimer == null) {
					mediaTimer = setInterval(function () {						
						// [ANDROID] [iOS] [WP]
						if (isAndroid || isiOS || isWP) {
							// get my_media position
							my_media.getCurrentPosition(							
								// success callback
								function (position) {
									if (position > -1)
										displayAudioPosition(position);

									if ((isWP) && (position > 0))
										currentPosition = position;
								},
								function (e) {
									console.log("Error getting pos=" + e);
								}
							);
						}
						// [BB]
						if (isBB) {
							displayAudioPosition(my_media.currentTime);
						}
					}, 1000);
				}
				// Play audio
				if (!isPlaying() && my_media) {
					my_media.play();
					isPlaying(true);
				} else if (my_media) {
					my_media.pause();
					isPlaying(false);
				}
				$('#seekbar').change(function () {
					if (my_media != null) {
						my_media.seekTo(this.value * 1000);
					}
				});
			}
		},

		displayAudioPosition = function (position) {
			var strPosition = "";
			if (my_media != null) {
				// [BB]
				if (isBB){
					soundDuration(my_media.duration);
				}
				// [WP] [iOS] [Android]
				if (isWP || isiOS || isAndroid){
					soundDuration(my_media.getDuration());	
				}
				
			}
			if (position < 0) {
				$('#seekbar').attr({
					"value": 0
				});
				$('#seekbar').val(0);
				strPosition = "00:00";
			} else {
				var totalSec = parseInt(position);
				$('#seekbar').val(totalSec);
				soundCurrentPossision(totalSec);
				var minutes = parseInt(totalSec / 60) % 60;
				var seconds = totalSec % 60;
				strPosition = (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
			}
			document.getElementById('time_playing').innerHTML = strPosition;
		},

		// Generate file name for audio file
		hashCode = function (s) {
			var temp = s.split("").reduce(function (a, b) {
				a = ((a << 5) - a) + b.charCodeAt(0);
				return a & a
			}, 0);
			if (temp < 0) {
				return (temp + "").substring(1);
			} else {
				return temp;
			}
		},

		// Show/hide player bar
		DisplayPlayer = function () {
			if (isJqmGhostClick()) {
				return;
			}
			if (entity().header.audioFile() == null || entity().header.audioFile() == "") {
				return;
			}
			if (bookVM.entity().overView.preview() == true) {
				showPopup(getLocalizeText('youMustGetSummaryBefore'));
				return;
			}
			if (entity().header.audioFile().indexOf("http://") == 0) {
				checkIfFileExists(strCatchFolder + "/" + hashCode(entity().header.audioFile()) + ".mp3");
			} else {
				isDisplayPlayer(!isDisplayPlayer());
				if (myScroll != null) {
					myScroll.refresh();
				}
			}
		},

		checkIfFileExists = function (path) {
			// [BB]
			if (isBB){
				if (localStore.get("Audio_" + path) != null) {
					fileExists(localPathForBB + path + ".mp3");
				} else {
					fileDoesNotExist();
				}
			}
			// [iOS] [WP] [Android]
			if (isiOS || isWP || isAndroid){
				var localFileSystem = LocalFileSystem.TEMPORARY;
				// [iOS]
				if (isiOS){
					localFileSystem = LocalFileSystem.PERSISTENT;
				}
				window.requestFileSystem(localFileSystem, 0, function (fileSystem) {
					fileSystem.root.getFile(path, {
						create: false
					}, fileExists, fileDoesNotExist);
				}, getFSFail);
			}
            
		},

		displayPopupMedia = function (path) {
            var localFileSystem = LocalFileSystem.TEMPORARY;
            // [iOS]
            if (isiOS){
                localFileSystem = LocalFileSystem.PERSISTENT;
            }
			window.requestFileSystem(localFileSystem, 0, function (fileSystem) {
				fileSystem.root.getFile(path, {
					create: false
				}, dontDisplayPopup, displayPopup);
			}, getFSFail);
		},

		displayPopup = function (fileEntry) {
			model.isDisplayPopupAdd(false);
			model.isDisplayPopupMedia(!model.isDisplayPopupMedia());
		},

		dontDisplayPopup = function () {
            model.isDisplayPopupAdd(!model.isDisplayPopupAdd());
            applyIscrollForFolder('wrapper_scroll_folder');
				
		},

		fileExists = function (fileEntry) {
			/* Only apply for ios */
            // [iOS]
            if (isiOS){
                entity().header.audioFile(fileEntry.fullPath);
            }
			// [BB]
			if (isBB){
				entity().header.audioFileDisplay(fileEntry);
			}
            // [ANDROID] [WP]
            if (isAndroid || isWP){
                entity().header.audioFile(fileEntry.toURI());
            }
			
			if (!needAddToFavorite) {
				isDisplayPlayer(!isDisplayPlayer());
				if (myScroll != null) {
					myScroll.refresh();
				}
			} else {
				needAddToFavorite = false;
				if (isLogin) {
					model.isDisplayPopupAdd(true);
					applyIscrollForFolder('wrapper_scroll_folder');
					return;
				}
				addToFavoriteItem(null);
			}
			
		},
		downloadSuccess = function (result) {
			hideLoadingDialog();
			isLoading = false;
			localStore.save("Audio_" + strCatchFolder + "/" + hashCode(entity().header.audioFile()) + ".mp3", "true");
			entity().header.audioFileDisplay(localPathForBB + strCatchFolder + '/' + hashCode(entity().header.audioFile()) + ".mp3");
			if (!needAddToFavorite) {
				isDisplayPlayer(!isDisplayPlayer());
				if (myScroll != null) {
					myScroll.refresh();
				}
			} else {
				needAddToFavorite = false;
				if (isLogin) {
					model.isDisplayPopupAdd(true);
					return;
				}
				addToFavoriteItem(null);
			}
		},
		downloadError = function (result) {
			hideLoadingDialog();
            isLoading = false;
			showPopup(getLocalizeText("failed"));
		},
		fileDoesNotExist = function () {
			/* Only apply for ios */
			if (navigator.connection.type == Connection.NONE) {
				showPopup(getLocalizeText("internetConnectionRequired"));
				return;
			}
			// [BB]
			if (isBB){
				showLoadingDialog();
				isLoading = true;
				try {
					var toPath = localPathForBB + strCatchFolder + '/' + hashCode(entity().header.audioFile()) + ".mp3";
					blackberry.io.filetransfer.download(entity().header.audioFile(), toPath, downloadSuccess, downloadError);
				} catch (e) {
					isLoading = false;
					hideLoadingDialog();
				}
				if (!needAddToFavorite) {
					//isDisplayPlayer(!isDisplayPlayer());
					if (myScroll != null) {
						myScroll.refresh();
					}
				}
			}
			else{
				// [iOS]
				if (isiOS){
					showLoadingDialog();
					isLoading = true;
					downloadFile(entity().header.audioFile());
				}
				else{
					if (!needAddToFavorite) {
						isDisplayPlayer(!isDisplayPlayer());
						if (myScroll != null) {
							myScroll.refresh();
						}
					} else {
						showLoadingDialog();
						downloadFile(entity().header.audioFile());
					}
				}
			}
			
			
			
		},

		getFSFail = function (evt) {
			hideLoadingDialog();
			isLoading = false;
			console.log(evt.target.error.code);
		},

		downloadFile = function (url) {
            
            var localFileSystem = LocalFileSystem.TEMPORARY;
            // [iOS]
            if (isiOS){
                localFileSystem = LocalFileSystem.PERSISTENT;
            }
			window.requestFileSystem(
				localFileSystem,
				0,
				function onFileSystemSuccess(fileSystem) {
					fileSystem.root.getFile("dummy.html", {
							create: true,
							exclusive: false
						},
						function gotFileEntry(fileEntry) {
							//var sPath = fileEntry.fullPath.replace("dummy.html", "");
							var sPath = fileEntry.fullPath.replace("dummy.html", "") + strCatchFolder + "/";
							var fileTransfer = new FileTransfer();
							fileEntry.remove();
							fileTransfer.download(
								url,
								sPath + hashCode(url) + ".mp3",
								function (theFile) {
									hideLoadingDialog();
									isLoading = false;
									// [iOS]
                                      if (isiOS){
                                        entity().header.audioFile(sPath + hashCode(url) + ".mp3");
                                      
                                      }
                                  // [ANDROID] [BB] [WP]
                                      if (isAndroid || isBB || isWP){
                                        entity().header.audioFile(theFile.toURI());
                                      }
									
									if (!needAddToFavorite) {
										isDisplayPlayer(!isDisplayPlayer());
										if (myScroll != null) {
											myScroll.refresh();
										}
									} else {
										needAddToFavorite = false;
										if (isLogin) {
											model.isDisplayPopupAdd(true);
											applyIscrollForFolder('wrapper_scroll_folder');
											return;
										}
									}
								},
								function (error) {
									hideLoadingDialog();
									isLoading = false;
									console.log("download error source " + error.source);
									console.log("download error target " + error.target);
									console.log("upload error code: " + error.code);
								}
							);
						},
						getFSFail
					);
				},
				getFSFail
			);
		},

		stopMedia = function () {
			if (my_media) {
				// [BB]
				if (isBB){
					my_media.pause();
				}
				// [iOS] [WP] [Android]
				if (isiOS || isWP || isAndroid){
					my_media.stop();
					my_media.release();
				}
				
				isPlaying(false);
			}
			isDisplayPlayer(false);
			if (myScroll != null) {
				myScroll.refresh();
			}
			soundDuration(0);
			clearInterval(mediaTimer);
			mediaTimer = null;
			my_media = null;
			
		},

		applyIscrollForFolder = function (strContentView) {
            if (folderScroll != null) {
				folderScroll.destroy();
				folderScroll = null;
			}
            
//			if (folderScroll != null) {
//				folderScroll.refresh();
//			} else {
				folderScroll = new iScroll(strContentView, {
					hScroll: false,
                    hideScrollbar: true
				});
				folderScroll.refresh();
//			}
		},

		back = function () {
			window.history.go(-1);
		},
        changeBackgroundToWhite = function()
        {
            backgroundColorName("white");
            textColorName("black");
            localStore.save("book_detail_background_color_name", "white");
            localStore.save("book_detail_text_color_name", "black");
            $(".book li").css({ color: textColorName() });
            $(".sub-heading").css({ color: textColorName() });
            $(".book li").css({ background: 'url(img/bullet.png) no-repeat', backgroundSize: '8px 8px', backgroundPosition: '10px ' + bookVM.topLi() + 'px'});

            isBuletWhite(false);
        },
        changeBackgroundToSepia = function()
        {
            backgroundColorName("#e1d4c4");
            textColorName("black");
            localStore.save("book_detail_background_color_name", "#e1d4c4");
            localStore.save("book_detail_text_color_name", "black");
            $(".book li").css({ color: textColorName() });
            $(".sub-heading").css({ color: textColorName() });
            $(".book li").css({ background: 'url(img/bullet.png) no-repeat', backgroundSize: '8px 8px', backgroundPosition: '10px ' + bookVM.topLi() + 'px'});
            isBuletWhite(false);
        },
        changeBackgroundToBlack = function()
        {
            backgroundColorName("black");
            textColorName("white");
            localStore.save("book_detail_background_color_name", "black");
            localStore.save("book_detail_text_color_name", "white");
            $(".book li").css({ color: textColorName() });
            $(".sub-heading").css({ color: textColorName() });
            $(".book li").css({ background: 'url(img/bullet-white.png) no-repeat', backgroundSize: '8px 8px', backgroundPosition: '10px ' + bookVM.topLi() + 'px'});
            isBuletWhite(true);
        },
        setTextColorDefault = function(){
            
            $(".book li").css({ color: textColorName() });
            $(".sub-heading").css({ color: textColorName() });

            if (!isBuletWhite()){
                $(".book li").css({ background: 'url(img/bullet.png) no-repeat', backgroundSize: '8px 8px', backgroundPosition: '10px ' + bookVM.topLi() + 'px'});
            }
            else{
                $(".book li").css({ background: 'url(img/bullet-white.png) no-repeat', backgroundSize: '8px 8px', backgroundPosition: '10px ' + bookVM.topLi() + 'px'});
            }
            $(".book li").css({ fontFamily: textFontName() + ', Times, serif !important' });
            setTimeout(function(){myScroll.refresh();}, 400);
        },
        createFontList = function(){
        	// [iOS]
        	if (isiOS){
	        	var fontNameListTemp = ['Antiqua', 'Arial' + ' ' + getLocalizeText('textDefault'), 'Blackletter', 'Calibri', 'Comic Sans',
	                'Courier', 'Cursive', 'Decorative', 'Fantasy', 'Fraktur', 'Frosty', 'Garamond', 'Georgia',
	                'Helvetica', 'Impact', 'Minion', 'Modern', 'Monospace', 'Palatino', 'Roman', 'Sans-serif',
	                'Serif', 'Script', 'Swiss', 'Times', 'Times New Roman', 'Verdana'];
	            fontNameList(fontNameListTemp);
        	}
        	
        	// [Android] [BB] [WP]
        	else{
	        	var fontNameListTemp = ['GaFont' + ' ' + getLocalizeText('textDefault'), 'DroidSerifRegular', 'DroidSans', 'RobotoRegular','DroidSansMono'];
				fontNameList(fontNameListTemp);
        	}
            
        },
        fontSelected = function(item){
            var itemTemplate = item.replace(getLocalizeText('textDefault'), "");
            textFontName(itemTemplate);
            localStore.save("book_detail_font_name", itemTemplate);
            
            /* chit code here. When user selected font name, I don't know why the text is break. So, I set font size again. it's ok */
            if (isAndroid){
	            increaseFontSize();
	            decreaseFontSize();
            }
            
            backAction(strBookDetail);
        },
        goToFontList = function(){
            model.viewFontList();
        },
		reloadLanguage = function () {
			strGetSummary(getLocalizeText('getSummary'));
			strComments(getLocalizeText('comments'));
			strShareEmail(getLocalizeText('shareEmail'));
			strShareEmailTo(getLocalizeText('eMail'));
			strShareEmailContent(getLocalizeText('comments'));
			strShareEmailBody(getLocalizeText('shareViaEmailBody'));
			strAnnotations(getLocalizeText('annotations'));
			strQuotes(getLocalizeText('quotes'));
			strRating = getLocalizeText('rating');
			strTakeAways = getLocalizeText('takeAways');
			strWhatYouWillLearn = getLocalizeText('whatYouWillLearn');
			strRecommendation = getLocalizeText('recommendation');
			strAbstract = getLocalizeText('abstract');
			strAboutTheAuthors = getLocalizeText('aboutTheAuthors');
			strThereAreCurrently(getLocalizeText('thereAreCurrently'));
			strCommentsOnThisTitle(getLocalizeText('commentsOnThisTitle'));
			strAddAComment(getLocalizeText('addAComment'));
			strPost(getLocalizeText('post'));
			strCancel(getLocalizeText('cancel'));
			strFavorites(getLocalizeText('favorites'));
			strWouldYouLike(getLocalizeText('wouldYouLikeTo'));
			strYes(getLocalizeText('yes'));
			strNo(getLocalizeText('no'));
			strTextOnly(getLocalizeText('textOnly'));
			strTextAndAudio(getLocalizeText('textAndAudio'));
            strFonts(getLocalizeText('fonts'));
            strBackground(getLocalizeText('background'));
            strWhite(getLocalizeText('white'));
            strSepia(getLocalizeText('sepia'));
            strBlack(getLocalizeText('black'));
		};

	return {
		entity: entity,
		getDetail: getDetail,
		title: title,
		isHaveAudio: isHaveAudio,
        isEditFont: isEditFont,
		back: back,
		fontSizeContent: fontSizeContent,
        fontName: fontName,
		topLi: topLi,
		fontSizeTitle: fontSizeTitle,
		fontSizeSubTitle: fontSizeSubTitle,
        showHideFontEdit: showHideFontEdit,
        setShowHideFontEdit: setShowHideFontEdit,
		increaseFontSize: increaseFontSize,
		decreaseFontSize: decreaseFontSize,
		hideBtnsShare: hideBtnsShare,
		isPlaying: isPlaying,
		isDisplayPlayer: isDisplayPlayer,
		DisplayPlayer: DisplayPlayer,
		playMedia: playMedia,
		stopMedia: stopMedia,
		bookID: bookID,
		numberFreeBooks: numberFreeBooks,
		activeBook: activeBook,
		buyTheBook: buyTheBook,
        viewComments: viewComments,
		comments: comments,
		getAnnotaions: getAnnotaions,
		postComments: postComments,
		postShareEmail: postShareEmail,
		listComment: listComment,
		listAnnotation: listAnnotation,
		strGetSummary: strGetSummary,
		strAudio: strAudio,
		strComments: strComments,
		strShareEmail: strShareEmail,
		strShareEmailTo: strShareEmailTo,
		strShareEmailContent: strShareEmailContent,
		strShareEmailBody: strShareEmailBody,
		strAnnotations: strAnnotations,
		strQuotes: strQuotes,
		strRating: strRating,
		strTakeAways: strTakeAways,
		strWhatYouWillLearn: strWhatYouWillLearn,
		strRecommendation: strRecommendation,
		strAbstract: strAbstract,
		strAboutTheAuthors: strAboutTheAuthors,
		strThereAreCurrently: strThereAreCurrently,
		strCommentsOnThisTitle: strCommentsOnThisTitle,
		strAddAComment: strAddAComment,
		strPost: strPost,
		strCancel: strCancel,
		strFavorites: strFavorites,
		strWouldYouLike: strWouldYouLike,
		strYes: strYes,
		strNo: strNo,
		strTextOnly: strTextOnly,
		strTextAndAudio: strTextAndAudio,
        strRemaining: strRemaining,
        strFonts: strFonts,
        strBackground: strBackground,
        strWhite: strWhite,
        strSepia: strSepia,
        strBlack: strBlack,

        heightOfScreen: heightOfScreen,
		soundDuration: soundDuration,
		soundCurrentPossision: soundCurrentPossision,
		addToFavorite: addToFavorite,
		addWithoutMedia: addWithoutMedia,
		addWithMedia: addWithMedia,
		closePopupMedia: closePopupMedia,
		addToFavoriteItem: addToFavoriteItem,
		FavoriteFolder: FavoriteFolder,
		FavoriteFolderLabel: FavoriteFolderLabel,
		buyTheBookHTML: buyTheBookHTML,
		shareSocialNetwork: shareSocialNetwork,
		shareFacebook: shareFacebook,
		shareTwitter: shareTwitter,
        shareLinkedIn: shareLinkedIn,
		shareEmail: shareEmail,
		reloadLanguage: reloadLanguage,
        changeBackgroundToWhite: changeBackgroundToWhite,
        changeBackgroundToSepia: changeBackgroundToSepia,
        changeBackgroundToBlack: changeBackgroundToBlack,
        setTextColorDefault: setTextColorDefault,
        fontSelected: fontSelected,
        goToFontList: goToFontList,
        backgroundColorName: backgroundColorName,
        textColorName: textColorName,
        isBuletWhite: isBuletWhite,
        fontNameList: fontNameList,
        textFontName: textFontName,
        applyIscrollForFolder: applyIscrollForFolder

	};
}()